const mysql = require("mysql");
const express = require("express");
const path = require("path");
const multer = require("multer");
const iconv = require("iconv-lite");
const cors = require("cors");

const app = express();
app.use(cors());
const router = express.Router();

/*************************** mysql 服务 *************************/
const mysqlOption = {
    host: "127.0.0.1",
    port: "3306",
    user: "root",
    password: "344300zhd",
    database: "file_service",
    connectTimeout: 2000
}

let mysqlPool;
mysqlRepool();

// 数据库连接池重连机制
function mysqlRepool(){
    mysqlPool = mysql.createPool({
        ...mysqlOption,
        waitForConnections: true,
        connectionLimit: 200,
        queueLimit: 0
    })
    mysqlPool.on("error", err => {
        err.code === "PROTOCOL_CONNECTTION_LOST" && setTimeout(mysqlRepool, 2000)
    })
    app.all("*", (_, __, next) => {
        mysqlPool.getConnection(err => {
            err && setTimeout(mysqlRepool, 2000) || next()
        })
    })
}

/**************************** 图片文件服务 **************************/
let file; // 上传的文件
let fileUrl = "/file/img";
let storage = multer.diskStorage({
    destination: path.resolve(__dirname, `.${fileUrl}`),
    filename: function(req, _file, cb){
        file = _file;
        // 解决中文名称乱码，原文件名存储，避免同一文件重复存储
        file.originalname = iconv.decode(_file.originalname, "UTF-8");
        file.filePath  = `http://127.0.0.1:8900${fileUrl}/${file.originalname}`
        cb(null, file.originalname);
    }
})

let fileFilter = function(req, file, cb){
    let acceptType = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
    if(acceptType.indexOf(file.mimetype) !== -1){
        cb(null, true); // 通过上传 
    }else{
        cb(null, false); // 禁止上传 
    }
}

let limits = {
    fileSize: "10MB"
}

const imageUploader = multer({
    fileFilter,
    storage,
    limits
}).single("file")

app.post("/image/uploadImage", imageUploader, (req, res) => {
    const {originalname, encoding, mimetype, filePath} = file;
    const sql = `insert into image (name, size, path, type) values ('${originalname}', '${encoding}', '${filePath}', '${mimetype}')`;
    mysqlPool.getConnection((err, conn) => {
        conn.query(sql, (err, result) => {
            if(err){
                res.json({
                    code: 0,
                    message: "图片上传失败",
                    data: err
                })
            }else{
                res.json({
                    code: 200,
                    message: "图片上传成功",
                    imgPath: file.filePath
                })
            }
        })
        mysqlPool.releaseConnection(conn);
    })
})

app.use(fileUrl, express.static(fileUrl)); // 文件静态访问

module.exports = { app, mysqlPool, router}

